﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CNotebook;
using CNotebook.Inventory;

namespace NotebookS2
{
    public partial class PhysicalCount : Form
    {
        public PhysicalCount()
        {
            InitializeComponent();
        }

        public string ConnectionString { get; set; }
        public bool IsMultipleWarehouse { get; set; }
        public string DefaultWarehouse { get; set; }

        public DataTable LineItems { get; set; }

        #region Functions

        public void ShowSearch()
        {
            FND_CNT oSearchDocument = new FND_CNT();

            oSearchDocument.ConnectionString = this.ConnectionString;
            oSearchDocument.ShowDialog();

            string sDocumentNumber = oSearchDocument.DocumentNumber;


            if (sDocumentNumber != null || sDocumentNumber.Trim() != "")
            {
                PhysicalCountManager oManager = new PhysicalCountManager();

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                DataRow oRow = oManager.GetDocument(sDocumentNumber);


                #region Header
                txtDocumentNumber.Text = oRow["DocNum"].ToString();
                cboWarehouse.EditValue = oRow["WhseCode"].ToString();
                txtStatus.Text = oRow["DocStatus"].ToString();
                txtRemarks.Text = oRow["Remarks"].ToString();
                dtPostDate.EditValue = (DateTime)oRow["PostingDate"];
              
                #endregion

                #region Line Items
                this.LineItems = oManager.GetLineItems(sDocumentNumber);
                gridControl1.DataSource = this.LineItems;
                gridControl1.Refresh();

                #endregion

                oManager.Close();

                btnAdd.Text = "Update";

            }

        }

        public void PrintPreview()
        {
            PRNT_CNT oPrint = new PRNT_CNT();

            oPrint.ConnectionString = this.ConnectionString;
            oPrint.DocumentNumber = txtDocumentNumber.Text;

            oPrint.WindowState = FormWindowState.Maximized;
            oPrint.ShowDialog();
        }
        
        DataTable GetTable()
        {
            DataTable _table = new DataTable();
            _table.Columns.Add("ItemCode", typeof(string));
            _table.Columns.Add("ItemName", typeof(string));
            _table.Columns.Add("UoM", typeof(string));
            _table.Columns.Add("UnitCount", typeof(double));
            _table.Columns.Add("UnitCost", typeof(double));
            _table.Columns.Add("LotNumber", typeof(string));
            _table.Columns.Add("MfrDate", typeof(DateTime));
            _table.Columns.Add("ExpiryDate", typeof(DateTime));

            return _table;
        }

        void InitializeSeries()
        {

            string ObjectType = "200";
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(ObjectType) == true)
            {
                txtDocumentNumber.Properties.ReadOnly = true;
                txtDocumentNumber.Text = "##########";

            }
            oSeries.Close();


        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _OBJECT_TYPE = "200";

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_OBJECT_TYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_OBJECT_TYPE);
            }
            else
            {
                _SERIES = txtDocumentNumber.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        void BindWarehouse()
        {
            WarehouseManager oManager = new WarehouseManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();
            DataTable oTable = new DataTable();

            oTable = oManager.GetWarehouse();



            cboWarehouse.Properties.DataSource = oTable;
            cboWarehouse.Properties.DisplayMember = "Dscription";
            cboWarehouse.Properties.ValueMember = "Code";
            DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

            col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Dscription", "Dscription", 100);

            col.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;

            cboWarehouse.Properties.Columns.Add(col);
            cboWarehouse.Properties.ShowHeader = false;
            
            oManager.Close();

        }

        void RemoveBlankLastRowFirst()
        {
            int iCount = -1;
            gridView1.MoveLast();

            int[] oRow = gridView1.GetSelectedRows();

            iCount = oRow[0];
            string sItemCode = "";


            sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

            if (sItemCode.Trim() == "")
            {
                gridView1.DeleteRow(iCount);
            }
        }

        void DisableControls()
        {
            txtStatus.Enabled = false;
            dtPostDate.Enabled = false;
            txtDocumentNumber.Properties.ReadOnly = true;
            cboWarehouse.Enabled = false;
            txtRemarks.Properties.ReadOnly = true;

            foreach (DevExpress.XtraGrid.Columns.GridColumn oCol in gridView1.Columns)
            {
                oCol.OptionsColumn.AllowEdit = false;
            }
        }

        void EnableControls()
        {
            dtPostDate.Enabled = true;
            txtDocumentNumber.Properties.ReadOnly = false;
            cboWarehouse.Enabled = true;
            txtRemarks.Properties.ReadOnly = false;

            foreach (DevExpress.XtraGrid.Columns.GridColumn oCol in gridView1.Columns)
            {
                if (oCol.Name == "UoM" || oCol.Name == "ItemName")
                {
                    oCol.OptionsColumn.AllowEdit = false;
                }
                else
                {
                    oCol.OptionsColumn.AllowEdit = true;
                }
            }
        }

        private void BindLotNumber(string sItemCode, DevExpress.XtraEditors.Repository.RepositoryItemComboBox oCbo)
        {
            StockManager oManager = new StockManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            DataTable _table = oManager.GetLotNumbers( sItemCode, this.cboWarehouse.EditValue.ToString());

            oManager.Close();
            oCbo.Items.Clear();
            foreach (DataRow oRow in _table.Rows)
            {
                oCbo.Items.Add(oRow["LotNumber"].ToString());
            }

        }
        #endregion

        private void PhysicalCount_Load(object sender, EventArgs e)
        {
            gridView1.HorzScrollVisibility = DevExpress.XtraGrid.Views.Base.ScrollVisibility.Always;
            dtPostDate.EditValue = System.DateTime.Now;
            BindWarehouse();

            cboWarehouse.EditValue = this.DefaultWarehouse;
            if (this.IsMultipleWarehouse == false)
            {
                cboWarehouse.Enabled = false;
            }

            InitializeSeries();

            this.LineItems = GetTable();

            gridControl1.DataSource = this.LineItems;
            gridControl1.Refresh();

            if (this.LineItems.Rows.Count == 0)
            {
                gridView1.AddNewRow();
                
            }   
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            PhysicalCountManager oManager = new PhysicalCountManager();
            PhysicalCountUnit oUnit = new PhysicalCountUnit();

            RemoveBlankLastRowFirst();
            if (btnAdd.Text == "Add")
            {
                
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();
                txtDocumentNumber.Text = GetNewSeries();
                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.Remarks = txtRemarks.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.WHCode = cboWarehouse.EditValue.ToString();
                oUnit.WHName = cboWarehouse.Text;

                oUnit.LineItems = this.LineItems;

                oManager.AddCountSheet(oUnit);
                oManager.Close();

                MessageBox.Show("Document successfully saved!!!", "Cycle Count", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                oUnit.DocumentNumber = txtDocumentNumber.Text;
                oUnit.PostingDate = (DateTime)dtPostDate.EditValue;
                oUnit.Remarks = txtRemarks.Text;
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.WHCode = cboWarehouse.EditValue.ToString();
                oUnit.WHName = cboWarehouse.Text;


                oUnit.LineItems = this.LineItems;
                oManager.UpdateCountSheet(oUnit);
                oManager.Close();

                MessageBox.Show("Document successfully updated!!!", "Cycle Count", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }



            btnAdd.Text = "Update";
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                int iCount = -1;
                int[] oRow = gridView1.GetSelectedRows();

                iCount = oRow[0];

                if (e.KeyCode == Keys.Delete)
                {
                    if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        gridView1.DeleteRow(iCount);
                    }
                }

                if (e.KeyCode == Keys.Down)
                {
                    if (gridView1.IsLastRow)
                    {
                        string sItemCode = "";
                        oRow = gridView1.GetSelectedRows();

                        iCount = oRow[0];
                        sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

                        if (sItemCode != "")
                        {
                            gridView1.AddNewRow();
                        }
                    }

                    gridControl1.Select();
                    gridView1.FocusedColumn = gridView1.Columns["ItemCode"];
                }
            }
            catch
            {
            }
        }

        private void txtItemCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            int iCount = -1;
            int[] oRow = gridView1.GetSelectedRows();

            iCount = oRow[0];

            FND_ITEM _FIND_ITEM = new FND_ITEM();

            _FIND_ITEM.ConnectionString = this.ConnectionString;

            _FIND_ITEM.ShowDialog();

            if (_FIND_ITEM.SelectedItemCode != null)
            {
                if (_FIND_ITEM.SelectedItemCode.Trim() != "")
                {
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemCode"], _FIND_ITEM.SelectedItemCode);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["ItemName"], _FIND_ITEM.SelectedItemDescription);
                    gridView1.SetRowCellValue(iCount, gridView1.Columns["UoM"], _FIND_ITEM.SelectedItemUnitMeasure);

                    BindLotNumber(_FIND_ITEM.SelectedItemCode, cboLotNumber);
                }
            }
        }
    
        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Applied")
            {
                btnAdd.Enabled = false;
                DisableControls();
                
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
            }

            if (txtStatus.Text == "Un-Applied")
            {
                btnAdd.Enabled = true;
                EnableControls();
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
            }

        }

        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (txtStatus.Text == "Un-Applied")
            {
                if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.OK)
                {

                    if (MessageBox.Show("Are you sure you want to apply this count sheet?", "Worksheet", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        PhysicalCountManager oManager = new PhysicalCountManager();

                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();


                        oManager.ApplyToInventory(txtDocumentNumber.Text);

                        oManager.Close();

                        txtStatus.Text = "Applied";
                        
                        

                        foreach (DataRow oRow in this.LineItems.Rows)
                        {
                            StockManager oStocks = new StockManager();

                            oStocks.ConnectionString = this.ConnectionString;
                            oStocks.Open();

                            if (oStocks.IsLotNumberExists(cboWarehouse.EditValue.ToString(), oRow["ItemCode"].ToString(), oRow["LotNumber"].ToString()) == true)
                            {
                                oStocks.SetStocks(cboWarehouse.EditValue.ToString(), oRow["ItemCode"].ToString(), oRow["LotNumber"].ToString(), oRow["UnitCount"].ToString());

                            }
                            else
                            {
                                oStocks.AddStocks(cboWarehouse.EditValue.ToString(), cboWarehouse.Text, oRow["ItemCode"].ToString(), oRow["ItemName"].ToString(), oRow["UnitCount"].ToString(), oRow["UoM"].ToString(), oRow["LotNumber"].ToString(), oRow["MfrDate"].ToString(), oRow["ExpiryDate"].ToString());
                            }

                            oStocks.Close();
                        }
                    }
                }

                if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Close)
                {
                    if (MessageBox.Show("Are you sure you want to cancel this count sheet?", "Worksheet", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        PhysicalCountManager oManager = new PhysicalCountManager();

                        oManager.ConnectionString = this.ConnectionString;
                        oManager.Open();

                        oManager.CancelDocument(txtDocumentNumber.Text);

                        oManager.Close();

                        txtStatus.Text = "Canceled";
                    }
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtItemCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                //gridControl1.Select();
                //gridView1.FocusedColumn = gridView1.Columns["LotNumber"];
                //gridView1.ShowEditor();
                
            }
        }

        private void txtItemCode_Leave(object sender, EventArgs e)
        {
            ItemManager oManager = new ItemManager();


            DevExpress.XtraEditors.TextEdit oTextEdit = (DevExpress.XtraEditors.TextEdit)sender;

            if (oTextEdit.Text != "")
            {
                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                DataTable _table = oManager.GetItemMasterData(oTextEdit.Text);

                oManager.Close();

                int iFocusRowHandle = gridView1.FocusedRowHandle;

                if (_table.Rows.Count == 1)
                {
                    DataRow oRow = _table.Rows[0];

                    oTextEdit.Text = oRow["ItemCode"].ToString();

                    gridControl1.Select();
                    gridView1.SetRowCellValue(iFocusRowHandle, gridView1.Columns["ItemName"], oRow["Description"].ToString());
                    gridView1.SetRowCellValue(iFocusRowHandle, gridView1.Columns["UoM"], oRow["InvtyUntMsr"].ToString());

                    gridControl1.Select();
                    gridView1.FocusedColumn = gridView1.Columns["LotNumber"];


                }
                else
                {

                    MessageBox.Show("No item found in the Item Master Data!!!", "Item", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
            }
        }


        private void PhysicalCount_Shown(object sender, EventArgs e)
        {

            gridControl1.Select();
            
            gridView1.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
            gridView1.FocusedColumn = gridView1.VisibleColumns[1];
            gridView1.ShowEditor();

            txtRemarks.Focus();
            
        }

        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {

            if (e.Column.FieldName == "")

                e.DisplayText = (e.RowHandle + 1).ToString();
        }

        private void cboLotNumber_Leave(object sender, EventArgs e)
        {
            gridControl1.Select();
            gridView1.FocusedColumn = gridView1.Columns["MfrDate"];
        }

        private void dtExpiryDate_Leave(object sender, EventArgs e)
        {
            gridControl1.Select();
            gridView1.FocusedColumn = gridView1.Columns["UnitCount"];
        }

        private void txtQty_EditValueChanged(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.TextEdit textQty = (DevExpress.XtraEditors.TextEdit)sender;
            int iQty = 0;
            try
            {
                iQty = Convert.ToInt16(textQty.Text);
            }
            catch
            {
                iQty = 0;
            }
            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["UnitCount"], iQty);
        }

        private void dtMfrDate_Leave(object sender, EventArgs e)
        {
            gridControl1.Select();
            gridView1.FocusedColumn = gridView1.Columns["ExpiryDate"];
        }

        private void txtUnitCost_EditValueChanged(object sender, EventArgs e)
        {
            DevExpress.XtraEditors.CalcEdit objectTxtBoxUnitCost = (DevExpress.XtraEditors.CalcEdit)sender;
            double sValue = 0;
            try
            {
                sValue =  Convert.ToDouble(objectTxtBoxUnitCost.EditValue);
            }
            catch { sValue = 0; }

            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["UnitCost"], sValue.ToString());
        }
    }
}
